//
//  ShopDetailsViewController.m
//  Findif
//
//  Created by Cicel Chen on 2018/10/22.
//  Copyright © 2018年 Cicel Chen. All rights reserved.
//

#import "ShopDetailsViewController.h"
#import "ShopDetailsHeaderView.h"
#import "HomeTableViewCell.h"
#import "GoodsDetailsViewController.h"
#import "GoodsModel.h"
#import "CouponModel.h"
#import "NewCouponTableViewCell.h"
#import <JMessage/JMessage.h>
#import "ChatRoomViewController.h"
#import "MapViewController.h"

@interface ShopDetailsViewController ()<UITableViewDelegate,UITableViewDataSource,ShopDetailsHeaderViewDelegate>

@property (nonatomic, weak)UITableView * tableView;
@property (nonatomic, strong)NSArray<GoodsModel *> * goodsArray;
@property (nonatomic, strong)NSDictionary * dict;
@property (nonatomic, strong)ShopDetailsHeaderView * headerView;
@property (nonatomic, weak)UIToolbar *toolbar;
@property (nonatomic, weak)UIView * couponView;
@property (nonatomic, weak)UITableView * couponTableView;
@property (nonatomic, strong)NSArray<CouponModel *> * couponArray;
@property (nonatomic, weak)UILabel * showLabel;

//店铺纬度
@property (nonatomic, copy)NSString * merchants_latitude;
//店铺经度
@property (nonatomic, copy)NSString * merchants_longitude;
//店铺名称
@property (nonatomic, copy)NSString * merchants_name;
//店铺地址
@property (nonatomic, copy)NSString * merchants_local;

@end

@implementation ShopDetailsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = ZRWhiteColor;
    
    [self setupNav];
    [self loadData];
    NSString * ID = [NSString stringWithFormat:@"%@",self.model.id];
    [self loadCouponDataWithShop_id:ID];
    [self setupUI];
}

- (void)loadCouponDataWithShop_id:(NSString *)shop_id{
    
    NSString * user_id = DEF_GET_OBJECT(@"id");
    
    [[ZRNetworkTool sharedTool] getMerchantsCouponsResultWithShop_id:shop_id WithUser_id:user_id WithBlock:^(BOOL success, id responseData) {
        
        if (success) {
            
            self.couponArray = [NSArray yy_modelArrayWithClass:[CouponModel class] json:responseData[@"data"]];
        }
    }];
}


- (void)loadData{
    
    if (self.model) {
       
        self.merchants_latitude = [NSString stringWithFormat:@"%@",self.model.merchants_latitude];
        self.merchants_longitude = [NSString stringWithFormat:@"%@",self.model.merchants_longitude];
        self.merchants_name = self.model.merchants_name;
        self.merchants_local = self.model.merchants_address;
        
        [[ZRNetworkTool sharedTool] getGoodsListResultWithShopid:self.model.id WithMerchants_goods_status:@"2" WithIs_merchants_get:@"0" WithBlock:^(BOOL success, id responseData) {
            
            if (success) {
                
                self.goodsArray = [NSArray yy_modelArrayWithClass:[GoodsModel class] json:responseData[@"data"]];
            }
        }];
    }else{
       
        [[ZRNetworkTool sharedTool] getGoodsListResultWithShopid:self.ID WithMerchants_goods_status:@"2" WithIs_merchants_get:@"0" WithBlock:^(BOOL success, id responseData) {
            
            if (success) {
                
                self.goodsArray = [NSArray yy_modelArrayWithClass:[GoodsModel class] json:responseData[@"data"]];
            }
        }];
        
        [[ZRNetworkTool sharedTool] getMerchantsInfoWithShop_id:self.ID WithBlock:^(BOOL success, id responseData) {

            if (success) {
                
                self.dict = responseData[@"data"];
                self.merchants_latitude = [NSString stringWithFormat:@"%@",self.dict[@"model.merchants_latitude"]];
                self.merchants_longitude = [NSString stringWithFormat:@"%@",self.dict[@"merchants_longitude"]];
                self.merchants_name = self.dict[@"merchants_name"];
                self.merchants_local = self.dict[@"merchants_address"];
            }
        }];
    }
}


- (void)setDict:(NSDictionary *)dict{
    
    _dict = dict;
    
    self.headerView.dict = dict;
}


- (void)setCouponArray:(NSArray<CouponModel *> *)couponArray{
    
    _couponArray = couponArray;
    
    [self.couponTableView reloadData];
}


- (void)setGoodsArray:(NSArray<GoodsModel *> *)goodsArray{
    
    _goodsArray = goodsArray;
    
    [self.tableView reloadData];
}

- (void)setupNav{
    
    self.title = @"店铺详情";
    
//    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back(1)"] style:UIBarButtonItemStylePlain target:nil action:nil];
//
//    self.navigationItem.backBarButtonItem = backItem;
}

- (void)setupUI{
    
    UITableView * tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = ColorWithRGB(0xF8F9FA);
    tableView.rowHeight = 120 * SCREENH6;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
    self.headerView =  [[ShopDetailsHeaderView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 460 * SCREENH6)];
    // 设置header
    if (self.model) {
        
        self.headerView.model = self.model;
    }
    self.headerView.shopDetailsHeaderViewDelegate = self;
    tableView.tableHeaderView = self.headerView;
    //    self.tableView.bounces = NO;
    //    self.tableView.estimatedRowHeight = 150 * SCREENH6;//估算高度
    //    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    self.tableView = tableView;
    
    [self.tableView registerClass:[HomeTableViewCell class] forCellReuseIdentifier:@"ShopDetailCell"];
    
    [self.view addSubview:self.tableView];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (self.couponArray.count == 0) {
        
        self.showLabel.hidden = NO;
    }else{
        
        self.showLabel.hidden = YES;
    }
    
    if (self.tableView == tableView) {
        
        return self.goodsArray.count;
    }else{
        
        return self.couponArray.count;
    }
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.tableView == tableView) {
       
        HomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ShopDetailCell" forIndexPath:indexPath];
        
        cell.model = self.goodsArray[indexPath.row];
        
        return cell;
    }else{
        
        NewCouponTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ShopDatailCouponCell" forIndexPath:indexPath];
        
        cell.model = self.couponArray[indexPath.row];
        
        return cell;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == self.couponTableView) {
        
        CouponModel * model = self.couponArray[indexPath.row];
        
        NewCouponTableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
        
        if ([cell.editLabel.text isEqualToString:@"领取"]) {
            
            NSString * coupon_id = [NSString stringWithFormat:@"%@",model.id];
            
            [[ZRNetworkTool sharedTool] userReceiveMerchantsCouponsResultWithCoupon_id:coupon_id WithBlock:^(BOOL success, id responseData) {
                
                if (success) {
                    
                    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                   message:@"恭喜你，领取成功快去使用吧！"
                                                                            preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                          handler:^(UIAlertAction * action) {
                                                                           
                                                                              NSString * ID = [NSString stringWithFormat:@"%@",self.model.id];
                                                                              [self loadCouponDataWithShop_id:ID];
                                                                              
                                                                          }];
                    
                    [alert addAction:defaultAction];
                    [self presentViewController:alert animated:YES completion:nil];
                }else{
                    
                    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                   message:responseData[@"message"]
                                                                            preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                          handler:^(UIAlertAction * action) {
                                                                              
                                                                          }];
                    
                    [alert addAction:defaultAction];
                    [self presentViewController:alert animated:YES completion:nil];
                }
            }];
        }
        
        
    }else{
        
        HiddenBar;
        
        GoodsModel * model = self.goodsArray[indexPath.row];
        
        GoodsDetailsViewController * detailVC = [GoodsDetailsViewController new];
        
        detailVC.ID = model.id;
        detailVC.infoType = [NSString stringWithFormat:@"%@",model.merchants_goods_type];
        
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}


- (void)clickCouponButton{
    
    [self setupCouponView];
}

- (void)setupCouponView{
    
    UIToolbar *toolbar = [[UIToolbar alloc]initWithFrame:[UIScreen mainScreen].bounds];
    //样式
    toolbar.barStyle = UIBarStyleBlackTranslucent;//半透明
    //透明度
    toolbar.alpha = 0.5f;
    toolbar.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
    [toolbar addGestureRecognizer:tapGR];
    
    self.toolbar = toolbar;
    [self.tabBarController.view addSubview:self.toolbar];
    
    UIView * couponView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenH - 300 * SCREENH6, kScreenW, 300 * SCREENH6)];
    
    couponView.backgroundColor = ZRWhiteColor;
    couponView.userInteractionEnabled = YES;
    
    self.couponView = couponView;
    
    [self.tabBarController.view addSubview:self.couponView];
    
    
    UIButton * closeButton = [UIButton new];
    
    [closeButton setImage:[UIImage imageNamed:@"关闭"] forState:UIControlStateNormal];
    [closeButton addTarget:self action:@selector(clickCloseButton) forControlEvents:UIControlEventTouchUpInside];
    
    [self.couponView addSubview:closeButton];
    
    
    UILabel * titleLabel = [UILabel new];
    
    titleLabel.text = @"优惠详情";
    titleLabel.textColor = ZRBlackColor;
    titleLabel.font = [UIFont boldSystemFontOfSize:15 * SCREENH6];
    
    [self.couponView addSubview:titleLabel];
    
    
    UIView * lineView = [UIView new];
    
    lineView.backgroundColor = ColorWithRGB(0xe4e4e4);
    
    [self.couponView addSubview:lineView];
    
    
    UILabel * showLabel = [UILabel new];
    
    showLabel.text = @"暂无优惠券";
    showLabel.textColor = ZRBlackColor;
    showLabel.font = [UIFont systemFontOfSize:15 * SCREENH6];
    showLabel.hidden = YES;
    
    self.showLabel = showLabel;
    
    [self.couponView addSubview:self.showLabel];
    
    
    UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 40 * SCREENH6, kScreenW, 270 * SCREENH6) style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = [UIColor clearColor];
        tableView.rowHeight = 105 * SCREENH6;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.couponTableView = tableView;
    
    [self.couponTableView registerClass:[NewCouponTableViewCell class] forCellReuseIdentifier:@"ShopDatailCouponCell"];
    
    [self.couponView addSubview:self.couponTableView];
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.couponView);
        make.top.mas_equalTo(self.couponView).offset(10 * SCREENH6);
    }];
    
    [closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(self.couponView).offset(-10 * SCREENH6);
        make.centerY.mas_equalTo(titleLabel);
        make.width.height.mas_equalTo(15 * SCREENH6);
    }];
    
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(self.couponView);
        make.height.mas_equalTo(1 * SCREENH6);
        make.top.mas_equalTo(self.couponView).offset(40 * SCREENH6);
    }];
    
    [self.showLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.couponTableView);
        make.centerY.mas_equalTo(self.couponTableView);
    }];
}

- (void)clickCloseButton{
    
    [self.toolbar removeFromSuperview];
    [self.couponView removeFromSuperview];
    [self.couponTableView removeFromSuperview];
}


- (void)tapAction{
    
    [self.toolbar removeFromSuperview];
    [self.couponView removeFromSuperview];
    [self.couponTableView removeFromSuperview];
}

- (void)pushToChat{
    
    NSString * merchants_admin_phone;
    if (self.model) {
        
        merchants_admin_phone = self.model.phone;
    }else{
        
       merchants_admin_phone = self.dict[@"merchants_admin_phone"];
    }
//    NSString * merchants_admin_phone = self.dict[@"merchants_admin_phone"];
    
    [JMSGConversation createSingleConversationWithUsername:merchants_admin_phone completionHandler:^(id resultObject, NSError *error) {
        
        if (error == nil) {
            HiddenBar;
            ChatRoomViewController * roomVC = [ChatRoomViewController new];
            
            roomVC.conversation = resultObject;
            
            [self.navigationController pushViewController:roomVC animated:YES];
            
        } else {
            
        }
    }];
}

- (void)pushToMapViewConteoller{
    
    ShowHUD;
    HiddenBar;
    
    MapViewController * mapVC = [MapViewController new];
    
    mapVC.merchants_latitude = self.merchants_latitude;
    mapVC.merchants_longitude = self.merchants_longitude;
    mapVC.merchants_name = self.merchants_name;
    mapVC.merchants_local = self.merchants_local;
    
    [self.navigationController pushViewController:mapVC animated:YES];
    
    HiddenHUD;
}



@end
